#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os

def write_cin_header(f):
    # 写入cin文件的标准头部配置
    header = """%name PinYin
%locale_name 拼音
%selkey 1234567890
%words_first false
%auto_select true
%auto_fix_up true
%enter_to_output_original true
%encoding SC
%custom_page_up_key ,
%custom_page_down_key .
%adjust_order_by_frequence true
%allow_changed true
%keyname begin
a a
b b
c c
d d
e e
f f
g g
h h
i i
j j
k k
l l
m m
n n
o o
p p
q q
r r
s s
t t
u u
v v
w w
x x
y y
z z
%keyname end
"""
    f.write(header)

def convert_txt_to_cin(txt_file, cin_file):
    try:
        # 读取txt文件中的词条
        entries = []
        with open(txt_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                # 解析格式：{count}pinyin word
                count_end = line.find('}')
                if count_end == -1:
                    continue
                count = line[1:count_end]
                rest = line[count_end + 1:].strip()
                space_pos = rest.rfind(' ')
                if space_pos == -1:
                    continue
                pinyin = rest[:space_pos]
                word = rest[space_pos + 1:]
                entries.append((pinyin, word))

        # 按拼音排序
        entries.sort(key=lambda x: x[0])

        # 写入cin文件
        with open(cin_file, 'w', encoding='utf-8') as f:
            # 写入头部
            write_cin_header(f)
            
            # 写入词条
            for pinyin, word in entries:
                f.write(f"{pinyin} {word}\n")

        print(f"转换完成！共转换{len(entries)}个词条")
        return True
    except Exception as e:
        print(f"转换失败：{str(e)}")
        return False

def main():
    if len(sys.argv) != 2:
        print("用法：python txt2cin.py <txt文件路径>")
        return

    txt_file = sys.argv[1]
    if not os.path.exists(txt_file):
        print(f"错误：文件 {txt_file} 不存在")
        return

    # 生成输出文件路径
    cin_file = os.path.splitext(txt_file)[0] + ".cin"
    
    # 转换文件
    if convert_txt_to_cin(txt_file, cin_file):
        print(f"转换后的文件已保存到：{cin_file}")

if __name__ == '__main__':
    main()